<!-- 学习监控 -->
<template>
    <div class="lean-container" ref="leanChart"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
    name: 'Lean',
    data() {
        return {
            chart: null,
            resizeTimer: null,
            chartConfig: {
                legend: ['课前', '课中', '课后', '平均值'],
                seriesTypes: [
                    { type: 'bar', width: 15, stack: 'one', color: '#056EA4', borderColor: '#00CCFF' },
                    { type: 'bar', width: 25, stack: 'two', color: '#3E268B', borderColor: '#7E2EC8' },
                    { type: 'bar', width: 15, stack: 'three', color: '#056F7B', borderColor: '#00CFA6' },
                    { type: 'line', color: '#ffa43a', borderColor: 'rgba(255, 234, 0, 0.5)' }
                ]
            },
            rankData: {
                number: [],
                mission: [],
                before: [],
                during: [],
                after: [],
                score: []
            },
            option: {
                animation: false,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow' },
                    backgroundColor: 'rgba(0, 24, 107, 0.8)',
                    borderColor: '#00CCFF',
                    borderWidth: 1,
                    textStyle: { color: '#fff', fontSize: 12 },
                    formatter: params => {
                        const title = `<div style="color:#00CCFF;font-size:14px;margin-bottom:5px;border-bottom:1px solid #00CCFF;padding-bottom:3px;">
                            ${params[0].axisValue}
                        </div>`
                        const content = params.map(item => `
                            <div style="margin: 3px 0;">
                                <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:${item.color};margin-right:5px;"></span>
                                <span style="color:#fff">${item.seriesName}：${item.value}</span>
                            </div>
                        `).join('')
                        return `<div style="padding: 3px;">${title}${content}</div>`
                    }
                },
                legend: {
                    data: [],
                    icon: 'circle',
                    itemWidth: 8,
                    itemHeight: 8,
                    top: '1%',
                    right: '14%',
                    textStyle: { fontStyle: 'normal', fontFamily: '微软雅黑', fontSize: 13, color: '#fff' }
                },
                grid: { top: '20%', right: '3%', left: '5%', bottom: '25%' },
                xAxis: [{
                    type: 'category',
                    axisLabel: { color: '#fff', interval: 0 },
                    axisLine: { lineStyle: { color: '#0a3e98' } },
                    axisTick: { show: false },
                    splitLine: { show: false },
                    data: []
                }],
                yAxis: [
                    {
                        type: 'value',
                        name: '成绩',
                        min: 0,
                        max: 100,
                        position: 'left',
                        nameTextStyle: { color: '#fff', fontSize: 11 },
                        axisLine: { lineStyle: { color: '#0a3e98' } },
                        axisTick: { show: false },
                        splitLine: { show: true, lineStyle: { color: '#0a3e98', type: 'dotted' } },
                        axisLabel: {
                            color: '#fff',
                            formatter: '{value}',
                            fontSize: 12
                        },
                        interval: 20,
                        scale: true,
                        splitNumber: 5
                    },
                    {
                        type: 'value',
                        position: 'right',
                        axisLine: { lineStyle: { color: '#0a3e98' } },
                        axisTick: { show: false },
                        splitLine: { show: false },
                        axisLabel: { show: false },
                        min: 0,
                        max: 100,
                        interval: 20,
                        scale: true,
                        splitNumber: 5
                    }
                ],
                dataZoom: [
                    { show: true, realtime: true, start: 0, end: 100, xAxisIndex: 0 },
                    { type: 'inside', realtime: true, start: 0, end: 100, xAxisIndex: 0 }
                ],
                series: []
            },
            // 初始化数据
            initData: {
                number: [1],
                mission: [1],
                before: [81],
                during: [76],
                after: [84],
                score: [80]
            }
        };
    },
    computed: {
        requestData() {
            return {
                studentClassId: this.$store.state.current,
                missionType: this.$store.state.mission
            };
        },
        // 根据missionType计算应该显示的数据
        visibleData() {
            const missionType = this.$store.state.mission;
            if (!this.rankData.mission || this.rankData.mission.length === 0) {
                return { ...this.rankData };
            }
            
            // 如果missionType为0，显示所有数据
            if (missionType === 0) {
                return this.rankData;
            }
            
            // 否则根据missionType筛选数据
            const visibleIndices = this.rankData.mission
                .map((mission, index) => ({ mission, index }))
                .filter(item => item.mission <= missionType)
                .map(item => item.index);
                
            return Object.fromEntries(
                Object.entries(this.rankData).map(([key, value]) => {
                    if (Array.isArray(value)) {
                        return [key, visibleIndices.map(idx => value[idx])];
                    }
                    return [key, value];
                })
            );
        }
    },
    watch: {
        requestData: {
            handler: 'fetchData',
            deep: true
        }
    },
    mounted() {
        // 先使用初始化数据渲染图表
        this.rankData = {...this.initData};
        this.initChart();
        
        // 然后尝试获取真实数据
        this.fetchData();
        window.addEventListener('resize', this.handleResize);
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.handleResize);
        this.chart?.dispose();
    },
    methods: {
        handleResize() {
            if (this.resizeTimer) {
                clearTimeout(this.resizeTimer);
            }
            this.resizeTimer = setTimeout(() => {
                this.chart?.resize();
            }, 200);
        },
        async fetchData() {
            try {
                this.chart?.showLoading({
                    text: '加载中...',
                    color: '#00CCFF',
                    textColor: '#fff',
                    maskColor: 'rgba(0, 0, 0, 0.1)'
                });
                const response = await this.$axios.post("/group/missionStats", this.requestData);
                if (response.data?.data) {
                    this.rankData = response.data.data;
                    this.initChart();
                }
            } catch (error) {
                console.error('请求失败', error);
            } finally {
                this.$nextTick(() => {
                    this.chart?.hideLoading();
                });
            }
        },
        initChart() {
            if (!this.chart) {
                this.chart = echarts.init(this.$refs.leanChart);
            }

            this.option.legend.data = this.chartConfig.legend;
            // 使用visibleData而非原始数据
            this.option.xAxis[0].data = this.visibleData.mission.map(mission => `任务${mission}`);
            this.option.series = this.chartConfig.seriesTypes.map((type, index) => {
                const dataKey = ['before', 'during', 'after', 'score'][index];
                const commonConfig = {
                    name: this.chartConfig.legend[index],
                    type: type.type,
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}',
                        // 只在折线图（平均值）上应用偏移
                        ...(type.type === 'line' ? { offset: [0, -10] } : {})
                    }
                };

                return type.type === 'bar' ? {
                    ...commonConfig,
                    barWidth: type.width,
                    stack: type.stack,
                    itemStyle: {
                        color: type.color,
                        borderColor: type.borderColor,
                        borderWidth: 1
                    },
                    // 使用visibleData中的数据
                    data: this.visibleData[dataKey] || []
                } : {
                    ...commonConfig,
                    yAxisIndex: 1,
                    smooth: false,
                    symbol: 'circle',
                    symbolSize: 2,
                    itemStyle: { color: type.color, borderColor: type.borderColor, borderWidth: 5 },
                    lineStyle: { color: type.color },
                    // 使用visibleData中的数据
                    data: this.visibleData[dataKey] || []
                };
            });

            this.chart.setOption(this.option);
        }
    }
};
</script>

<style scoped>
.lean-container {
    width: 100%;
    height: 80%;
}
</style>